<template>
  <div class="cart-page" :class="{'loading': isLoading}">
    <Header />

    <main class="cart-container">
      <div class="cart-header">
        <h1 class="cart-title">我的购物车</h1>
        <!-- <p class="cart-subtitle" v-if="cartData.items.length > 0">
          {{ cartData.total }} 件商品 · 共 {{ total.toFixed(2) }} 元
        </p> -->
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-overlay">
        <div class="spinner"></div>
      </div>

      <!-- 购物车为空状态 -->
      <div v-if="!isLoading && cartData.value?.records?.length === 0" class="empty-cart fade-in">
        <div class="empty-cart-icon pulse-animation">
          <svg width="100" height="100" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9 22C9.55228 22 10 21.5523 10 21C10 20.4477 9.55228 20 9 20C8.44772 20 8 20.4477 8 21C8 21.5523 8.44772 22 9 22Z" stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M20 22C20.5523 22 21 21.5523 21 21C21 20.4477 20.5523 20 20 20C19.4477 20 19 20.4477 19 21C19 21.5523 19.4477 22 20 22Z" stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M1 1H5L7.68 14.39C7.77144 14.8504 8.02191 15.264 8.38755 15.5583C8.75318 15.8526 9.2107 16.009 9.68 16H19.4C19.8693 16.009 20.3268 15.8526 20.6925 15.5583C21.0581 15.264 21.3086 14.8504 21.4 14.39L23 6H6" stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h3 class="empty-cart-title">购物车是空的</h3>
        <p class="empty-cart-desc">快去挑选心仪的商品吧</p>
        <router-link to="/" class="continue-shopping-btn scale-animation">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="mr-2">
            <path d="M12 19L5 12L12 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          继续购物
        </router-link>
      </div>

      <!-- 购物车内容 -->
      <div v-else class="cart-content">
        <!-- 调试信息 -->
        <div class="debug-info-row bg-yellow-100 p-4 mb-4 rounded flex flex-wrap gap-6">
          <div class="debug-info-item">购物车商品数量: {{ cartData.items.length }}</div>
          <div class="debug-info-item">总商品数: {{ cartData.total }}</div>
          <div class="debug-info-item">当前页: {{ cartData.pageNo }} / {{ cartData.totalPages }}</div>
          <div class="debug-info-item">选择商品数: {{ selectedItems.length }}</div>
        </div>

        <!-- 批量操作栏 -->
        <div class="batch-actions bg-white rounded-lg shadow-sm p-3 mb-3 flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <label class="flex items-center">
              <input
                type="checkbox"
                :checked="isAllSelected"
                @change="toggleSelectAll"
                class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
              >
              <span class="ml-2 text-gray-700">全选</span>
            </label>
            <span class="text-gray-500">已选择 {{ selectedItems.length }} 件商品</span>
          </div>
          <div class="flex space-x-2">
            <button
              v-if="selectedItems.length > 0"
              @click="batchDelete"
              class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm"
            >
              批量删除
            </button>
            <button
              @click="clearCart"
              class="px-3 py-1 border border-red-300 text-red-600 rounded hover:bg-red-50 text-sm"
            >
              清空购物车
            </button>
          </div>
        </div>

        <!-- 商品表格 -->
        <div class="cart-table-wrapper">
          <table class="cart-table">
            <thead>
              <tr>
                <th style="width:40px;"><input type="checkbox" :checked="isAllSelected" @change="toggleSelectAll" /></th>
                <th style="width:100px;">商品图片</th>
                <th>商品信息</th>
                <th style="width:120px;">单价</th>
                <th style="width:120px;">数量</th>
                <th style="width:120px;">小计</th>
                <th style="width:60px;">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in cartData.items" :key="item.id" :class="{'highlighted': isHighlighted(item.id)}" @mouseenter="highlightItem(item.id)" @mouseleave="unhighlightItem()">
                <td><input type="checkbox" :checked="selectedItems.includes(item.id.toString())" @change="toggleSelectItem(item.id)" /></td>
                <td>
                  <img :src="item.image || item.img || item.mainImage || item.imageUrl || defaultImage" :alt="item.name" class="cart-table-img" @error="handleImageError" />
                </td>
                <td>
                  <div class="cart-table-name">{{ item.name }}</div>
                  <div class="cart-table-brand">{{ item.brand || '无品牌' }}</div>
                </td>
                <td>
                  <span class="cart-table-price">¥{{ (item.price || 0).toFixed(2) }}</span>
                  <span v-if="item.discountPrice" class="cart-table-discount">¥{{ (item.discountPrice || 0).toFixed(2) }}</span>
                </td>
                <td>
                  <div class="cart-table-quantity">
                    <button @click="decreaseQuantity(item.id)" :disabled="item.count <= 1">-</button>
                    <span>{{ item.count }}</span>
                    <button @click="increaseQuantity(item.id)">+</button>
                  </div>
                </td>
                <td>
                  <span class="cart-table-total">¥{{ ((item.price || 0) * item.count).toFixed(2) }}</span>
                </td>
                <td>
                  <button class="cart-table-remove" @click="removeItem(item.id)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页组件 -->
        <div v-if="cartData.totalPages > 1" class="pagination-container bg-white rounded-lg shadow-sm p-4 mt-6">
          <div class="flex items-center justify-between">
            <div class="text-gray-600">
              共 {{ cartData.total }} 件商品，第 {{ cartData.pageNo }} / {{ cartData.totalPages }} 页
            </div>
            <div class="flex space-x-2">
              <button
                @click="changePage(cartData.pageNo - 1)"
                :disabled="cartData.pageNo <= 1"
                class="px-3 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                上一页
              </button>
              <span class="px-3 py-2 text-gray-700">
                {{ cartData.pageNo }}
              </span>
              <button
                @click="changePage(cartData.pageNo + 1)"
                :disabled="cartData.pageNo >= cartData.totalPages"
                class="px-3 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                下一页
              </button>
            </div>
          </div>
        </div>

        <!-- 购物车侧边栏 -->
        <div class="cart-sidebar">
          <div class="cart-summary bg-white rounded-xl shadow-sm p-6 sticky top-24">
            <h3 class="summary-title text-lg font-semibold text-gray-800 mb-6">订单摘要</h3>
            <div class="summary-item py-3 border-b border-gray-100 mt-4">
              <span class="text-gray-600">已选商品</span>
              <span class="font-medium">{{ selectedItems.length }} 件</span>
            </div>
            <div class="summary-item py-3 border-b border-gray-100 mt-4">
              <span class="text-gray-600">已选商品总价</span>
              <span class="font-medium">¥{{ selectedTotal.toFixed(2) }}</span>
            </div>
            <div class="summary-item py-2">
              <span class="text-gray-600">优惠券</span>
              <span>
                <select v-model="selectedCouponId" class="coupon-select">
                  <option :value="''">不使用优惠券</option>
                  <option v-for="c in coupons" :key="c.id" :value="c.id">
                    {{ c.name }}（{{ c.desc }}）
                  </option>
                </select>
              </span>
            </div>
            <div class="summary-item py-2">
              <span class="text-gray-600">优惠金额</span>
              <span class="text-green-600 font-medium">-¥{{ couponDiscount.toFixed(2) }}</span>
            </div>
            <div class="summary-divider my-4"></div>
            <div class="summary-total py-3">
              <span class="text-lg font-semibold text-gray-800">应付总计</span>
              <span class="text-xl font-bold text-red-600">¥{{ finalTotal.toFixed(2) }}</span>
            </div>
            <div class="cart-actions space-y-3 mt-6">
              <button
                class="checkout-btn w-full py-3 px-4 bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-semibold rounded-lg shadow-md hover:shadow-lg transform hover:-translate-y-0.5 transition-all"
                @click="checkout"
              >
                立即结算
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <Footer />

    <!-- 结算弹窗 -->
    <div v-if="showCheckoutModal" class="checkout-modal-overlay">
      <div class="checkout-modal">
        <h2 class="modal-title">选择收货地址</h2>
        <form @submit.prevent="submitOrder">
          <div class="modal-form-group">
            <label>收货地址</label>
            <select v-model="selectedAddressId" required>
              <option :value="null" disabled>请选择收货地址</option>
              <option v-for="addr in addresses" :key="addr.id" :value="addr.id">
                {{ addr.area }} {{ addr.otherName }}（{{ addr.name }} {{ addr.phone }}）
              </option>
            </select>
          </div>
          <div class="modal-form-group">
            <label>备注</label>
            <textarea v-model="orderForm.remark" placeholder="选填"></textarea>
          </div>
          <div class="modal-summary">
            <div>共 {{ selectedItems.length }} 件商品</div>
            <div>总价：<span class="modal-total">¥{{ selectedTotal.toFixed(2) }}</span></div>
            <div>优惠：<span class="modal-total">-¥{{ couponDiscount.toFixed(2) }}</span></div>
            <div>应付：<span class="modal-total">¥{{ finalTotal.toFixed(2) }}</span></div>
          </div>
          <div class="modal-actions">
            <button type="button" class="modal-cancel" @click="showCheckoutModal = false">取消</button>
            <button type="submit" class="modal-confirm" :disabled="addresses.length === 0">确认下单</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '../store/cart'
import { getCartList, removeFromCart, updateCartItem, clearCart as clearCartAPI, batchDeleteCartItems } from '../api/cart'
import { getQuan } from '../api/user'
import Header from '../components/Header.vue'
import Footer from '../components/Footer.vue'
import { getAddressPage, type AddressResponse } from '../api/address'
import { createOrder } from '../api/order'

const router = useRouter()
const cartStore = useCartStore()
const defaultImage = 'https://picsum.photos/200/200?random=1'

// 分页参数
const pagination = ref({
  pageNo: 1,
  pageSize: 10
})

// 商品高亮状态
const highlightedItemId = ref('')

// 计算属性
const cartData = computed(() => cartStore.cartData)
const selectedItems = computed(() => cartStore.selectedItems)
const isLoading = computed(() => cartStore.isLoading)
const isAllSelected = computed(() => cartStore.isAllSelected)

// 只统计已选商品的总价
const selectedTotal = computed(() => {
  let total = 0
  cartData.value.items.forEach((item: CartItem) => {
    if (selectedItems.value.includes(item.id.toString())) {
      total += (item.discountPrice || item.price) * item.count
    }
  })
  return total
})

// 优惠券相关
interface Coupon {
  id: string;
  name: string;
  type: string;
  min: number;
  value: number;
  desc: string;
  checked: boolean;
  expire?: boolean;
  expireTime?: string;
}
const coupons = ref<Coupon[]>([])
const selectedCouponId = ref('')
const couponDiscount = computed(() => {
  if (!selectedCouponId.value) return 0
  const coupon = coupons.value.find((c: Coupon) => c.id === selectedCouponId.value)
  if (!coupon) return 0
  if (coupon.type === '满减') {
    return selectedTotal.value >= coupon.min ? coupon.value : 0
  } else if (coupon.type === '折扣') {
    return selectedTotal.value * (1 - coupon.value)
  }
  return 0
})
const finalTotal = computed(() => {
  const t = selectedTotal.value - couponDiscount.value
  return t > 0 ? t : 0
})

// 自动识别最优优惠券
function autoSelectBestCoupon() {
  let best: Coupon | null = null
  let maxDiscount = 0
  for (const c of coupons.value) {
    let discount = 0
    if (c.type === '满减' && selectedTotal.value >= c.min) discount = c.value
    if (c.type === '折扣') discount = selectedTotal.value * (1 - c.value)
    if (discount > maxDiscount) {
      maxDiscount = discount
      best = c
    }
  }
  selectedCouponId.value = best ? best.id : null
}

// 加载购物车数据
const loadCart = async () => {
  cartStore.setLoading(0)
  try {
    const response = await getCartList(pagination.value)
    cartStore.setCartData(response)
    cartStore.clearSelection()
  } catch (error) {
    cartStore.clear()
  } finally {
    cartStore.setLoading(false)
  }
}

// 分页切换
const changePage = async (pageNo: number) => {
  if (pageNo < 1 || pageNo > cartData.value.totalPages) return
  pagination.value.pageNo = pageNo
  await loadCart()
}

// 增加商品数量
const increaseQuantity = async (id: string | number) => {
  try {
    const item = cartData.value.items.find((i: any) => i.id === id)
    if (item) {
      await updateCartItem(id, item.count + 1)
      await loadCart()
    }
  } catch (error) {}
}

// 减少商品数量
const decreaseQuantity = async (id: string | number) => {
  try {
    const item = cartData.value.items.find((i: any) => i.id === id)
    if (item && item.count > 1) {
      await updateCartItem(id, item.count - 1)
      await loadCart()
    }
  } catch (error) {}
}

// 移除商品
const removeItem = async (id: string | number) => {
  if (confirm('确定要移除该商品吗？')) {
    try {
      await batchDeleteCartItems([id])
      await loadCart()
    } catch (error) {}
  }
}

// 清空购物车
const clearCart = async () => {
  if (confirm('确定要清空购物车吗？')) {
    try {
      await clearCartAPI()
      await loadCart()
    } catch (error) {}
  }
}

// 批量删除
const batchDelete = async () => {
  // 统一将id转为字符串并过滤无效id
  const ids = selectedItems.value.map(id => String(id)).filter(Boolean)
  if (ids.length === 0) {
    alert('请选择要删除的商品')
    return
  }
  if (confirm(`确定要删除选中的 ${ids.length} 件商品吗？`)) {
    try {
      await batchDeleteCartItems(ids)
      await loadCart()
    } catch (error) {}
  }
}

// 切换选择单个商品
const toggleSelectItem = (id: string | number) => {
  cartStore.toggleSelectItem(id.toString())
}

// 切换全选
const toggleSelectAll = () => {
  cartStore.toggleSelectAll()
}

// 结算
const showCheckoutModal = ref(false)
const orderForm = ref({
  name: '',
  phone: '',
  address: '',
  remark: ''
})

const addresses = ref<AddressResponse[]>([])
const selectedAddressId = ref<number | null>(null)
const selectedAddress = computed(() => addresses.value.find(a => a.id === selectedAddressId.value) || null)

// 拉取地址列表
const loadAddresses = async () => {
  try {
    const res = await getAddressPage({ page: 1, size: 10 })
    if (res.code === 200 && res.data) {
      addresses.value = res.data.records || []
    } else {
      addresses.value = []
    }
  } catch {
    addresses.value = []
  }
}

// 打开结算弹窗时拉取地址
watch(showCheckoutModal, (v) => { if (v) loadAddresses() })

onMounted(() => { loadAddresses() })

const submitOrder = async () => {
  if (!selectedAddressId.value) {
    alert('请选择收货地址')
    return
  }
  if (selectedItems.value.length === 0) {
    alert('请选择要结算的商品')
    return
  }
  // 组装下单参数
  const productIds: number[] = []
  const numbers: number[] = []
  cartData.value.items.forEach((item: CartItem) => {
    if (selectedItems.value.includes(item.id.toString())) {
      productIds.push(Number(item.productId || item.id))
      numbers.push(Number(item.count))
    }
  })
  if (productIds.length === 0) {
    alert('请选择要结算的商品')
    return
  }
  const quanId = selectedCouponId.value ? Number(selectedCouponId.value) : 0
  try {
    const res = await createOrder({ productIds, numbers, addressId: Number(selectedAddressId.value), quanId, isShoppingCart: 1 })
    if (res && res.code === 200 && res.data && res.data.orderId) {
      alert('下单成功！请前往我的订单页支付')
      showCheckoutModal.value = false
      router.push('/user')
    } else {
      alert(res.message || '下单失败！')
    }
  } catch (e) {
    alert('下单失败！')
  }
}

const checkout = () => {
  if (selectedItems.value.length === 0) {
    alert('请先选择要结算的商品')
    return
  }
  showCheckoutModal.value = true
}

// 高亮商品
const highlightItem = (id: string | number) => {
  highlightedItemId.value = id.toString()
}
const unhighlightItem = () => {
  highlightedItemId.value = ''
}
const isHighlighted = (id: string | number) => {
  return highlightedItemId.value === id.toString()
}
const handleImageError = () => {}

// 组件挂载时加载购物车和优惠券
onMounted(async () => {
  await loadCart()
  try {
    const res = await getQuan({ pageNum: 1, pageSize: 10 })
    // 适配后端返回结构
    coupons.value = (res.quanVOs || []).map((q: any) => ({
      id: String(q.bagId), // 优惠券唯一标识
      name: q.name,
      type: '满减', // 这里假设所有券都是满减类型，如有其他类型请补充判断
      min: q.userLimitValue || 0, // 最低使用金额
      value: q.value || 0, // 优惠金额
      desc: q.description || '',
      expire: q.expire,
      expireTime: q.expireTime,
      checked: false // 默认未选中
    }))
    console.log('优惠券数据:', coupons.value)
    autoSelectBestCoupon()
  } catch (e) {
    coupons.value = []
    selectedCouponId.value = ''
    console.log('获取优惠券失败', e)
  }
})
// 监听已选商品变化，自动选最优券
watch(selectedTotal, () => {
  autoSelectBestCoupon()
})

// 购物车商品类型定义（本地）
interface CartItem {
  id: string | number;
  productId?: string | number;
  name: string;
  price: number;
  count: number;
  imageUrl?: string;
  mainImage?: string;
  img?: string;
  image?: string;
  brand?: string;
  discountPrice?: number;
  userId?: number;
  amount?: number;
  number?: number;
}
</script>

<style scoped>
/* 基础样式 */
:root {
  --primary-color: #e5ff00;
  --secondary-color: #0ee306;
  --accent-color: #f97316;
  --success-color: #10b981;
  --danger-color: #ef4444;
  --warning-color: #f59e0b;
  --info-color: #06b6d4;
  --light-color: #f8fafc;
  --dark-color: #1e293b;
}

.cart-page {
  min-height: 100vh;
width:100vw;
  background-color: #f1f5f9;
  transition: all 0.3s ease;
}

.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 16px;
}

.cart-header {
  text-align: center;
  margin-bottom: 32px;
  position: relative;
}

.cart-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--dark-color);
  margin: 0 0 8px 0;
  background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.cart-subtitle {
  color: #64748b;
  font-size: 1rem;
  margin: 0;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(59, 130, 246, 0.1);
  border-left-color: #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 空购物车样式 */
.empty-cart {
  text-align: center;
  padding: 100px 20px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.01);
  max-width: 600px;
  margin: 0 auto;
  opacity: 0;
  transform: translateY(20px);
  animation: fadeIn 0.5s ease-out forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.empty-cart-icon {
  margin-bottom: 32px;
  position: relative;
}

.pulse-animation {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.empty-cart-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: #475569;
  margin: 0 0 16px 0;
}

.empty-cart-desc {
  color: #94a3b8;
  margin: 0 0 32px 0;
  font-size: 1.1rem;
}

.continue-shopping-btn {
  display: inline-block;
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: white;
  padding: 14px 40px;
  border-radius: 30px;
  text-decoration: none;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 1rem;
}

.continue-shopping-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 15px 30px -5px rgba(59, 130, 246, 0.4);
}

.scale-animation {
  animation: scale 0.3s ease-out;
}

@keyframes scale {
  0% { transform: scale(0.95); }
  100% { transform: scale(1); }
}

/* 购物车内容样式 */
.cart-content {
  display: grid;
  grid-template-columns: 1fr 340px;
  gap: 32px;
}

/* 批量操作栏样式 */
.batch-actions {
  margin-bottom: 24px;
}

/* 购物车商品项样式 */
.cart-item {
  display: grid;
  grid-template-columns: 40px 120px 1fr 120px 100px 40px;
  gap: 16px;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.cart-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 复选框样式 */
.item-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 商品图片样式 */
.item-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.highlight-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 8px;
}

/* 商品信息样式 */
.item-info {
  padding: 0 16px;
}

.item-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 8px;
  line-height: 1.4;
}

.item-brand {
  color: #64748b;
  font-size: 0.9rem;
  margin-bottom: 12px;
}

.item-price {
  font-size: 1.3rem;
  font-weight: 700;
  color: #ef4444;
}

/* 数量控制样式 */
.item-quantity {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  border: 1px solid #e2e8f0;
  border-radius: 50%;
  background: white;
  color: #64748b;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.quantity-btn:hover {
  background: #f8fafc;
  border-color: #cbd5e1;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-number {
  min-width: 40px;
  text-align: center;
  font-weight: 600;
  color: #1e293b;
}

/* 总价样式 */
.item-total {
  text-align: center;
}

.total-price {
  font-size: 1.2rem;
  font-weight: 700;
  color: #1e293b;
}

/* 删除按钮样式 */
.remove-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 50%;
  background: #fef2f2;
  color: #ef4444;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.remove-btn:hover {
  background: #fee2e2;
  transform: scale(1.1);
}

/* 分页样式 */
.pagination-container {
  margin-top: 24px;
}

/* 购物车侧边栏样式 */
.cart-sidebar {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.cart-summary {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.summary-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.summary-divider {
  height: 1px;
  background: #e2e8f0;
  margin: 16px 0;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 2px solid #e2e8f0;
}

.coupon-section {
  margin-top: 20px;
}

.coupon-section input {
  border: 1px solid #d1d5db;
  border-radius: 8px 0 0 8px;
  padding: 12px 16px;
  font-size: 0.9rem;
}

.coupon-section button {
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 0 8px 8px 0;
  padding: 12px 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s ease;
}

.coupon-section button:hover {
  background: #2563eb;
}

/* 购物车操作按钮样式 */
.cart-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.checkout-btn {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  color: white;
  border: none;
  border-radius: 12px;
  padding: 16px 24px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.checkout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

/* 购物提示样式 */
.cart-tips {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.cart-tips h4 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
}

.cart-tips ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.cart-tips li {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  color: #64748b;
  font-size: 0.9rem;
}

/* 结算弹窗样式 */
.checkout-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.checkout-modal {
  background: #fff;
  border-radius: 18px;
  padding: 36px 32px 28px 32px;
  width: 95%;
  max-width: 420px;
  box-shadow: 0 12px 40px rgba(0,0,0,0.18);
  margin: 0 auto;
  animation: fadeInUp 0.4s;
  position: relative;
}

@keyframes fadeInUp {
  from { opacity: 0; transform: translateY(40px);}
  to { opacity: 1; transform: translateY(0);}
}

.modal-title {
  font-size: 2rem;
  font-weight: 800;
  color: #22223b;
  text-align: center;
  margin-bottom: 28px;
  letter-spacing: 1px;
}

.modal-form-group {
  margin-bottom: 22px;
}

.modal-form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #3b3b3b;
  font-size: 1.08rem;
}

.modal-form-group select,
.modal-form-group textarea {
  width: 100%;
  border-radius: 10px;
  border: 1.5px solid #e0e7ef;
  padding: 12px 14px;
  font-size: 1rem;
  background: #f8fafc;
  transition: border 0.2s;
  margin-top: 2px;
  box-sizing: border-box;
}

.modal-form-group select:focus,
.modal-form-group textarea:focus {
  border: 1.5px solid #3b82f6;
  outline: none;
  background: #fff;
}

.modal-form-group select {
  appearance: none;
  background: #f8fafc url('data:image/svg+xml;utf8,<svg fill="gray" height="20" viewBox="0 0 20 20" width="20" xmlns="http://www.w3.org/2000/svg"><path d="M7.293 7.293a1 1 0 011.414 0L10 8.586l1.293-1.293a1 1 0 111.414 1.414l-2 2a1 1 0 01-1.414 0l-2-2a1 1 0 010-1.414z"/></svg>') no-repeat right 12px center/18px 18px;
}

.modal-summary {
  background: #f6f8fa;
  border-radius: 12px;
  padding: 18px 12px;
  margin: 18px 0 0 0;
  text-align: center;
  font-size: 1.08rem;
  box-shadow: 0 2px 8px #e0e7ef33;
}

.modal-total {
  font-size: 1.18rem;
  font-weight: 700;
  color: #ef4444;
}

.modal-actions {
  display: flex;
  gap: 16px;
  margin-top: 28px;
}

.modal-cancel,
.modal-confirm {
  flex: 1;
  padding: 13px 0;
  border-radius: 10px;
  font-weight: 700;
  font-size: 1.08rem;
  cursor: pointer;
  transition: all 0.18s;
  border: none;
}

.modal-cancel {
  background: #f3f4f6;
  color: #374151;
  border: 1.5px solid #e0e7ef;
}

.modal-cancel:hover {
  background: #e0e7ef;
}

.modal-confirm {
  background: linear-gradient(90deg, #3b82f6, #6366f1);
  color: #fff;
  box-shadow: 0 2px 8px #3b82f633;
  border: none;
}

.modal-confirm:disabled {
  background: #cbd5e1;
  color: #fff;
  cursor: not-allowed;
  box-shadow: none;
}

.modal-confirm:hover:enabled {
  background: linear-gradient(90deg, #2563eb, #6366f1);
  transform: translateY(-2px) scale(1.03);
}

@media (max-width: 600px) {
  .checkout-modal {
    padding: 18px 6vw 18px 6vw;
    max-width: 98vw;
  }
  .modal-title {
    font-size: 1.3rem;
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .cart-content {
    grid-template-columns: 1fr;
  }

  .cart-sidebar {
    order: -1;
  }
}

@media (max-width: 768px) {
  .cart-container {
    padding: 16px 12px;
  }

  .cart-item {
    grid-template-columns: 1fr;
    gap: 12px;
    text-align: center;
  }

  .item-image {
    width: 100%;
    height: 200px;
  }

  .item-quantity {
    justify-content: center;
  }

  .item-total {
    text-align: center;
  }

  .remove-btn {
    justify-self: center;
  }

  .checkout-modal {
    width: 95%;
    padding: 24px;
  }

  .modal-actions {
    flex-direction: column;
  }
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.transition-all {
  transition: all 0.3s ease;
}

.duration-300 {
  transition-duration: 300ms;
}

.hover\:shadow-md:hover {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.cart-table-wrapper {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  padding: 0;
  margin-bottom: 24px;
  overflow-x: auto;
}
.cart-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 15px;
}
.cart-table th, .cart-table td {
  padding: 14px 8px;
  text-align: center;
  border-bottom: 1px solid #f1f5f9;
}
.cart-table th {
  background: #f8fafc;
  color: #64748b;
  font-weight: 500;
}
.cart-table-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #f1f5f9;
}
.cart-table-name {
  font-weight: 600;
  color: #1e293b;
  text-align: left;
}
.cart-table-brand {
  color: #94a3b8;
  font-size: 13px;
  text-align: left;
}
.cart-table-price {
  color: #ef4444;
  font-weight: 600;
}
.cart-table-discount {
  color: #94a3b8;
  text-decoration: line-through;
  margin-left: 6px;
  font-size: 13px;
}
.cart-table-quantity {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}
.cart-table-quantity button {
  width: 28px;
  height: 28px;
  border: 1px solid #e2e8f0;
  background: #fff;
  color: #64748b;
  border-radius: 4px;
  font-size: 18px;
  cursor: pointer;
  transition: background 0.2s;
}
.cart-table-quantity button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.cart-table-total {
  color: #1e293b;
  font-weight: 700;
}
.cart-table-remove {
  background: none;
  color: #ef4444;
  border: none;
  cursor: pointer;
  font-size: 15px;
  padding: 0 8px;
  border-radius: 4px;
  transition: background 0.2s;
}
.cart-table-remove:hover {
  background: #fee2e2;
}
tr.highlighted {
  background: #f0f9ff;
}

@media (max-width: 1024px) {
  .cart-content {
    grid-template-columns: 1fr;
  }
  .cart-sidebar {
    order: -1;
  }
  .cart-table-img {
    width: 60px;
    height: 60px;
  }
}
@media (max-width: 768px) {
  .cart-table th, .cart-table td {
    padding: 8px 2px;
    font-size: 13px;
  }
  .cart-table-img {
    width: 40px;
    height: 40px;
  }
}

.debug-info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
  align-items: center;
}
.debug-info-item {
  min-width: 160px;
  font-size: 15px;
  color: #92400e;
  font-weight: 500;
}
@media (max-width: 600px) {
  .debug-info-row {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  .debug-info-item {
    min-width: 0;
  }
}

.coupon-select {
  padding: 4px 8px;
  border-radius: 6px;
  border: 1px solid #d1d5db;
  font-size: 15px;
  margin-left: 8px;
}
</style>
